let token = JSON.parse(localStorage.getItem('token'))

$('#layui-laypage-1').click(function() {
    alert(1)
})

//初始化渲染数据
let d = {
    pagenum: 1,
    pagesize: 2,
    cate_id: '',
    state: ''
}

getAticList(token, function(data) {
    data.data.forEach(value => {
        let temp = `<option value="${value.Id}">${value.name}</option>`
        $('.layui-form .cate_id').append(temp)
    })
    layui.form.render()
})

//初始化渲染
renderFirst()

function renderFirst() {
    getIdAticle(token, d, function(data) {
        let total = data.total
        render(data.data)
        layui.use('laypage', function() {
            var laypage = layui.laypage;
            //执行一个laypage实例
            laypage.render({
                elem: 'test1', //注意，这里的 test1 是 ID，不用加 # 号
                layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
                limits: [2, 3, 5, 10],
                limit: d.pagesize,
                count: total, //数据总数，从服务端得到
                jump: function(obj, first) {
                    // console.log(obj.count)
                    // console.log(first)
                    // console.log(obj.limit)
                    // console.log(obj.curr)
                    d.pagenum = obj.curr
                    d.pagesize = obj.limit
                    if (!first) {
                        getIdAticle(token, d, function(data) {
                            render(data.data)
                        })
                    }
                }
            });
        });
    })
}



//封装一个渲染数据
function render(arr) {
    $('.layui-table tbody').empty()
    arr.forEach(value => {
        let temp = `
        <tr>
            <td>${value.title}</td>
            <td>${value.cate_name}</td>
            <td>${value.pub_date}</td>
            <td>${value.state}</td>
            <td data-id="${value.Id}">
                <button type="button" class="layui-btn layui-btn-sm edite">编辑</button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger del">删除</button>
            </td>
        </tr>
        `
        $('.layui-table tbody').append(temp)
    });
}


//分类列表提交，数据筛选
layui.form.on('submit(formDemo)', function(data) {
    console.log(data.field)
    d.cate_id = data.field.cate_id - 0
    d.state = data.field.state
    renderFirst()
    return false;
});

// 删除功能

$('.layui-table tbody').on('click','.del',function(){
    let id = $(this).parent().attr('data-id')
    delIdAticle(token,id,function(res){
        if(res.status !== 0){
            layer.msg(res.message)
        }else{
            layer.msg(res.message)
            renderFirst()
        }
    })  
})
